class ResourcesController < ApplicationController
  
    layout 'default'
    
  # GET /resources
  # GET /resources.xml
  def index
  if (params[:sort_by]) then
  	if(params[:sort_by] == "title") then
  		if(params[:this_resources]) then
  		flash[:notice] = "HEREEEEEE"
  			@resources_ids = params[:this_resources]
  			counter = 0
  			@resources = []
  			while(counter < @resources_ids.length) do
				@resources << Resource.find((@resources_ids[counter]).to_i)
				counter += 1
			end
# 			@resources = session[:current_resources_bla]
			@resources = @resources.sort {|res1,res2| res1.title <=> res2.title}
  		else
  			query = "Select * from resources ORDER BY title ;"
  			@resources = Resource.find_by_sql(query)
  		end
  	end
  	if(params[:sort_by] == "updated_at") then
  		if(params[:this_resources]) then
  			@resources = params[:resources]
			@resource = @resource.sort {|res1,res2| res1.updated_at <=> res2.updated_at}
  		else
  			query = "Select * from resources ORDER BY updated_at DESC;"
  			@resources = Resource.find_by_sql(query)
  		end
  	end
  	if(params[:sort_by] == "grade") then
  		if(params[:this_resources]) then
  			@resources = params[:resources]
			@resource = @resource.sort {|res1,res2| res1.grade.evaluation <=> res2.grade.evaluation}
  		else
  			query =  "SELECT DISTINCT R.id, R.title, R.link , R.description ,R.user_id, R.created_at , R.updated_at FROM resources R , Grades G WHERE  R.id = G.resource_id ORDER BY G.evaluation DESC;"
  		@resources = Resource.find_by_sql(query)
  		end
  	end
  	
  else
  	if(params[:favorites]) then 
  		favorites = Favorite.find(:all , :conditions => "user_id = #{session[:user_id]}")
  	end
  	if(params[:recommended]) then
    	query = Resource.recommendedQuery(session[:user_id])
		@resources = Resource.find_by_sql(query)
  	else
  		if(params[:tag_id]) then
  			@tag = Tag.find(params[:tag_id])
			query =  "SELECT R.id, R.title, R.link , R.description ,R.user_id, R.created_at , R.updated_at FROM resources R, tag_events T WHERE T.tag_id = '#{@tag.id}' AND T.resource_id = R.id ORDER BY R.updated_at DESC;"
   			if(!session[:multiple_tags].nil?) then
				query = Resource.multiTagQuery(session[:multiple_tags], @tag)
			end
		else 
			query = "Select * from resources ORDER BY updated_at DESC;"
			@tag = nil
		end
		@resources = Resource.find_by_sql(query)
		if(!session[:multiple_tags].nil?) then
			@resources = Resource.resourcesForMultipleTags(session[:multiple_tags], @resources)
		end
  	end
  end
#   	session[:current_resources_bla] = @resources
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @resources }
    end
  end




def set_multiple_tag
	session[:multiple_tags] = []
	render :text => "SET"
end

def no_multiple_tag
	session[:multiple_tags] = nil
	render :text => "NOT SET"
# 	redirect_to :action => "index" 
end

	def indexResourcesByTag
		query = "SELECT * FROM resources R, tag_events T, grades G WHERE T.tag_id = '#{params[:tag_id]}' AND T.resource_id = R.id;"
		@resources = Resource.find_by_sql(query)
		render :template => "resources/index"
	end
  # GET /resources/1
  # GET /resources/1.xml
  def show
    @resource = Resource.find(params[:id])
    query = "Select T.name, T.id from tags T, tag_events TE where  TE.resource_id = '#{@resource.id}' AND T.id = TE.tag_id;"
    @tags = Tag.find_by_sql(query)
    if(@tags.nil?) then
     @tags = []
   end   
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @resource }
    end
  end

  # GET /resources/new
  # GET /resources/new.xml
  #prepares the form for creating a new resource
  def new
    @resource = Resource.new
     @user = User.find(session[:user_id]) unless session[:user_id] == nil
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @resource }
    end
  end

  # GET /resources/1/edit
  def edit
#   puts "\n\nedit ~~~\n\n"
#   if params[:id] = "edit" then
#   	puts	 "\nasd\n\n"
#   	@resource = Resource.find(params[:resId])
#   else
#   	@resId = params
    @resource = Resource.find(params[:id])
#     end
  end





  # POST /resources
  # POST /resources.xml
  def create

   @resource = Resource.new(params[:resource])
   @resource.user_id = session[:user_id]
   #@resource.link = @resource.link.delete "http://" 
   #@resource.link = "http://" << @resource.link
    if @resource.link[0..6] != "http://" then
     @resource.link = "http://" << @resource.link 
    end
   

   
   @resource.save
	  
  if(params[:video]) then
  @tag = Tag.find(:first ,:conditions => [ "name = ?", "video"])
  	if(@tag.nil?) 
		@tag = Tag.createTagWithName("video")
  	end
  @tag_event =	TagEvent.createTagEventFromTagUserResource(@tag.id,session[:user_id],@resource.id) if ((TagEvent.find(:first , :conditions => "tag_id = #{@tag.id} AND resource_id = #{@resource.id} AND user_id = #{session[:user_id]}")).nil?)
  end
  if(params[:audio]) then
  @tag = Tag.find(:first ,:conditions => [ "name = ?", "audio"])
    if(@tag.nil?) 
	  @tag = Tag.createTagWithName("audio")
  	end
  	 @tag_event =	TagEvent.createTagEventFromTagUserResource(@tag.id,session[:user_id],@resource.id) if ((TagEvent.find(:first , :conditions => "tag_id = #{@tag.id} AND resource_id = #{@resource.id} AND user_id = #{session[:user_id]}")).nil?)
  end
  if(params[:text]) then
    @tag = Tag.find(:first , :conditions => [ "name = ?", "text"])
      if(@tag.nil?) 
		@tag = Tag.createTagWithName("text")
	  end
	   @tag_event =	TagEvent.createTagEventFromTagUserResource(@tag.id,session[:user_id],@resource.id) if ((TagEvent.find(:first , :conditions => "tag_id = #{@tag.id} AND resource_id = #{@resource.id} AND user_id = #{session[:user_id]}")).nil?)
  end

  
  	respond_to do |format|
      if @resource.save
        flash[:notice] = ' Resource was successfully created.'
        format.html { redirect_to(@resource) }
        format.xml  { render :xml => @resource, :status => :created, :location => @resource }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @resource.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /resources/1
  # PUT /resources/1.xml
  def update
    @resource = Resource.find(params[:id])
  if(params[:video]) then
  @tag = Tag.find(:first ,:conditions => [ "name = ?", "video"])
  	if(@tag.nil?) 
		@tag = Tag.createTagWithName("video")
  	end
  	if ((TagEvent.find(:first , :conditions => "tag_id = #{@tag.id} AND resource_id = #{@resource.id} AND user_id = #{session[:user_id]}")).nil?) then
  	puts "AAAAAAARRRRRRRGGGGGGGGGHHHHHHHHHH ***********"
 	 @tag_event =	TagEvent.createTagEventFromTagUserResource(@tag.id,session[:user_id],@resource.id) 
    end
  end
  if(params[:audio]) then
  @tag = Tag.find(:first ,:conditions => [ "name = ?", "audio"])
    if(@tag.nil?) 
	  @tag = Tag.createTagWithName("audio")
  	end
  @tag_event =	TagEvent.createTagEventFromTagUserResource(@tag.id,session[:user_id],@resource.id) if ((TagEvent.find(:first , :conditions => "tag_id = #{@tag.id} AND resource_id = #{@resource.id} AND user_id = #{session[:user_id]}")).nil?)
  end
  if(params[:text]) then
    @tag = Tag.find(:first , :conditions => [ "name = ?", "text"])
      if(@tag.nil?) 
		@tag = Tag.createTagWithName("text")
	  end
  @tag_event =	TagEvent.createTagEventFromTagUserResource(@tag.id,session[:user_id],@resource.id) if ((TagEvent.find(:first , :conditions => "tag_id = #{@tag.id} AND resource_id = #{@resource.id} AND user_id = #{session[:user_id]}")).nil?)
  end
    respond_to do |format|
      if @resource.update_attributes(params[:resource])
        flash[:notice] = 'Resource was successfully updated.'
        format.html { redirect_to(@resource) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @resource.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /resources/1
  # DELETE /resources/1.xml
  def destroy
    @resource = Resource.find(params[:id])
    @resource.destroy

    respond_to do |format|
      format.html { redirect_to(resources_url) }
      format.xml  { head :ok }
    end
  end
  
  
  def filteredIndex
   	case params[:tag]
  	when "no_tag"
		query = "Select * from resources;"
		@tag = nil
	else 
	@tag = Tag.find(params[:tag_id])
	query =  "SELECT R.id, R.title, R.link , R.description ,R.user_id, R.created_at , R.updated_at FROM resources R, tag_events T WHERE T.tag_id = '#{@tag.id}' AND T.resource_id = R.id;"
	end
   	@resources = Resource.find_by_sql(query)

    render :partial => 'filteredIndex'

  end
  

  
  def resourcesofuser
    id = params[:id]
    @user = User.find(id)
    query = "Select * from resources where user_id = '#{@user.id}';"
    @resources = Resource.find_by_sql(query)
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @resources }
    end
  end
  
  
  
  def display2 
    @resource = Resource.find(1)
  #  render :template=>"/display2"
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @resource }
    end
  end
  
  
  
  #vote
  def vote
    parameters=params[:id].split(":")
    res_id = parameters[0]
    grade = parameters[1]
  	fromUserId = session[:user_id]
    query = "Select * from grades where resource_id = '#{res_id}' and user_id = '#{session[:user_id]}';"
    @grade = Grade.find_by_sql(query)
    if (@grade.length != 0) then
      flash[:notice] = "You cannot vote twice this resource"
    else
      query = "Select * from users where id = (Select user_id from resources where id = #{res_id});"
      @resOwner = (User.find_by_sql(query))[0]  
      #until here it's almost ok, but then...
      
      puts "\n\n"
      # why is it an Array ???
      puts @resOwner.class
      puts "\n\n"
      
      #this should call the method in the User_controller... but it's an Array...
#       @resOwner.incrementKarma(grade.to_f)
      @resOwner.incrementKarmaFromOtherUser(grade.to_f, fromUserId)
      
      @grade = Grade.new({:user_id=>session[:user_id], :resource_id=>res_id, :evaluation=>grade})
      @grade.save
      #flash[:notice] = "updatato"
    end
#     redirect_to :action=>"index" , :tag => "no_tag"
    redirect_to :back
  end
  
  
  def live_search
    @phrase = params[:find]
        
    if(!@phrase.nil? and @phrase != "") then 
      a1 = "%"
      a2 = "%"
      @searchphrase = a1 + @phrase + a2
      @resources = @results = Resource.find(:all, :conditions => [ "description LIKE ? or title LIKE ?", @searchphrase, @searchphrase])
      @number_match = @results.length
      render(:layout => false)
     else render :text=>""
     end
  end
  
  def addFavoriteResource
  	Favorite.addFavorite(params[:user_id],params[:id])
  	#redirect_to :back
    @resource = Resource.find(params[:id])
    render :partial=>"generalTemplates/add_remove_favourites"
  end
  
  def deleteFavoriteResource
  	Favorite.deleteFavorite(params[:user_id],params[:id])
  	#redirect_to :back
    @resource = Resource.find(params[:id])
    render :partial=>"generalTemplates/add_remove_favourites"
  end
  
    def addFavoriteResourceOneDiv
  	Favorite.addFavorite(params[:user_id],params[:id])
  	#redirect_to :back
    @resource = Resource.find(params[:id])
    render :partial=>"generalTemplates/add_remove_favourites_from_precise_div"
  end
  
  def deleteFavoriteResourceOneDiv
  	Favorite.deleteFavorite(params[:user_id],params[:id])
  	#redirect_to :back
    @resource = Resource.find(params[:id])
    render :partial=>"generalTemplates/add_remove_favourites_from_precise_div"
  end
  
end
